﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace HRM.Lib
{
    public class ConfigXML
    {
        private string strPathFileName = Config.strAppPath + "HRMConfig.xml";
        private XmlDocument xmlDoc = new XmlDocument();

        protected internal string GetKey(string strKey)
        {
            try
            {
                string strValue = "";
                this.xmlDoc.Load(strPathFileName);
                XmlNode appSettingsNode = this.xmlDoc.SelectSingleNode("configuration/appSettings");
                foreach (XmlNode childNode in appSettingsNode)
                {
                    if (childNode.Attributes["key"].Value == strKey)
                    {
                        strValue = childNode.Attributes["value"].Value;
                        break;
                    }
                }
                return strValue;
            }
            catch
            {
                return "";
            }
        }

        private bool KeyExists(string strKey)
        {
            this.xmlDoc.Load(strPathFileName);
            XmlNode appSettingsNode = this.xmlDoc.SelectSingleNode("configuration/appSettings");
            foreach (XmlNode childNode in appSettingsNode)
            {
                if (childNode.Attributes["key"].Value == strKey)
                {
                    return true;
                }
            }
            return false;
        }

        protected internal void UpdateKey(string strKey, string strNewValue)
        {
            this.xmlDoc.Load(strPathFileName);
            if (!this.KeyExists(strKey))
            {
                throw new ArgumentNullException("Key", "<" + strKey + "> does not exist in the configuration. Update failed.");
            }
            XmlNode appSettingsNode = this.xmlDoc.SelectSingleNode("configuration/appSettings");
            foreach (XmlNode childNode in appSettingsNode)
            {
                if (childNode.Attributes["key"].Value == strKey)
                {
                    childNode.Attributes["value"].Value = strNewValue;
                }
            }
            this.xmlDoc.Save(strPathFileName);
        }
    }
}
